/**
 * Created by Administrator on 2016/7/11.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'model',
    'dialog',
    'datepicker'
], function ($, common, ready, template, Model, dialog, datepicker) {
    var other_file = 0;
    var index = function () {
        this.init();
    };

    index.prototype = {

        init: function () {
            var _this = this;

            //地区
            $.ajax({
                url: _global.url.api + 'regions',
                type: 'get',
                async: false,
                data: {depth: 2},
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('region', res.data);
                    }
                }
            });

            this.fetch();
            this.event();
        },
        fetch: function () {
            var _this = this;

            $('#main-view').html(template('add-tpl', {region: this.region}));

            this.model = new Model({
                url: _global.url.api + 'records',
                data: {}
            });
        },
        set: function ($k, $v) {
            this[$k] = $v;
        },
        event: function () {
            var _this = this;
            //添加品牌
            $('#btn-brand').on('click', function (e) {
                e.preventDefault();
                if (typeof _this.model.data.brand_id == 'undefined') {
                    _this.model.data.brand_id = [];
                }
                dialog({
                    title: '添加品牌',
                    width: 400,
                    content: template('add-brand-tpl'),
                    ok: function () {
                        var brandVal = $('#brand').val();

                        if (brandVal == '') {
                            alert('品牌不能为空');
                            return false;
                        }
                        $.ajax({
                            url: _global.url.api + 'brand',
                            data: {brand: brandVal},
                            dataType: 'json',
                            type: 'get',
                            success: function (d) {
                                if (d.code == 0) {
                                    Alert({
                                        msg: '添加成功'
                                    });
                                }
                                var el_brand = $('<span class="label label-info mr10 id="' + d.data['brand_id'] + '">' + brandVal +
                                '<a href="" style="color: #fff"><span class="glyphicon glyphicon-remove"></span></a></span>');
                                $('#brand-name').append(el_brand);

                                _this.model.data.brand_id.push(d.data['brand_id']);
                            },
                            error: function () {
                                Alert({msg: '该品牌已被代理', type: 'error'});
                            }

                        });
                    }, cancel: function () {
                    }
                }).show(e.target);
            });

            //地区联动
            $('.province').on('change', function () {
                $('select[name="city"]').html('');
                var id = $(this).val();
                var city = _this.region[id].child;
                for (var n in city) {
                    $('select[name="city"]').append('<option value="' + city[n].id + '">' + city[n].name + '</option>')
                }
            });

            $('input,select,textarea').on('change', function (e) {
                _this.change(e);
            });

            //保存事件
            $('#btn-save').on('click', function (e) {
                e.preventDefault();
                if (_this.model.data.cate_id == undefined || _this.model.data.cate_id == []) {
                    alert('请选择分类');
                    return false;
                }

                if (_this.model.data.brand_id == undefined || _this.model.data.brand_id == []) {
                    alert('请添加品牌');
                    return false;
                }

                _this.model.data.other_file = other_file;
                _this.model.data.city = $('[name="city"]').val();
                _this.model.data.contact = $('[name="contact"]').val();
                _this.model.data.address = $('[name="address"]').val();
                _this.model.data.tel = $('[name="tel"]').val();
                _this.model.data.mobile = $('[name="mobile"]').val();

                if ($('[name="password"]').val() != undefined) {
                    _this.model.data.password = $('[name="password"]').val();
                }
                _this.model.valid_config = {
                    'name': 'required'
                };

                if (_this.model.post()) {
                    //_this.fetch();
                    window.location.reload();
                } else {

                }
            });

            //测试号，显示登录帐号区域
            $('input[name="is_test"]').on('click', function () {
                var input_value = $(this).val();
                if (input_value == 1) {
                    document.getElementById("login_area").style.display = 'block';
                } else {
                    document.getElementById("login_area").style.display = 'none';
                }
            });

            //选择分类
            $('#btn-cate').on('click', function (e) {
                e.preventDefault();
                if (typeof _this.model.data.cate_id == 'undefined') {
                    _this.model.data.cate_id = [];
                }
                //一级分类
                _this.cate_form = $(template('cate-tpl', {}));

                //分类
                $.ajax({
                    url: _global.url.api + 'categorys',
                    type: 'get',
                    async: false,
                    data: {depth: 1},
                    success: function (res) {
                        if (res.code == 0) {
                            $.each(res.data, function (n, v) {
                                _this.cate_form.find('[name="cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
                            });
                        }
                    }
                });

                //显示二级分类，并联动
                //bind change event
                _this.cate_form.find('[name="cate"]').on('change', function () {
                    _this.cate_form.find('[name="child-cate"]').html('');
                    var id = typeof $(this).val() == 'object' ? $(this).val()[0] : $(this).val();

                    $.ajax({
                        url: _global.url.api + 'categorys',
                        type: 'get',
                        async: false,
                        data: {depth: 1, pid: id},
                        success: function (res) {
                            if (res.code == 0) {
                                $.each(res.data, function (n, v) {
                                    _this.cate_form.find('[name="child-cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
                                });
                            }
                        }
                    });

                });
                //显示弹框
                _this.dialog = dialog({
                    content: _this.cate_form,
                    width: 400,
                    ok: function () {
                        isAdd = false;
                        $.each(_this.cate_form.find('select[name="child-cate"]')[0].selectedOptions, function (n, option) {
                            console.log('_this.model.data.cate_id', typeof(_this.model.data.cate_id));
                            $.each(_this.model.data.cate_id, function (n, v) {
                                if (v == option.value) {
                                    alert('该分类已添加');
                                    isAdd = true;
                                    return false;
                                }
                            });
                            if (isAdd) {
                                return false;
                            }
                            var el_cate = $('<span class="label label-info mr10" id="' + option.value + '">' + option.text +
                            ' <a href="" style="color: #fff"><span class="glyphicon glyphicon-remove"></span></a></span>');
                            $('#cate-name').append(el_cate);
                            _this.model.data.cate_id.push(option.value);
                        });
                        _this.cate_form.remove();

                    }, cancel: function () {
                    }
                }).show(e.target);
            });

            //分类删除
            $('body').on('click', '#cate-name a', function (e) {
                e.preventDefault();
                $(this).parent().remove();
                _this.model.data.cate_id.remove($(this).parent().attr('id'));
            });

            //删除品牌
            $('body').on('click', '#brand-name a', function (e) {
                e.preventDefault();
                $(this).parent().remove();
                _this.model.data.brand_id.remove($(this).parent().attr('id'));
            });


            //上传附件

            $('body').on('click', '#btn-upload', function (e) {
                _this.upload_dialog = dialog({
                    content: template('upload-tpl', {}),
                    width: 550,
                    ok: function () {
                        var affix = $("#upload-frame")[0].contentWindow.affix.get();
                        _this.affixPreview(affix);
                    }, cancel: function () {
                    }
                });
                _this.upload_dialog.show();
            });
        },
        change: function (e) {
            this.model.data[$(e.target).attr('name')] = $(e.target).val();
        },
        affixPreview: function (affix) {
            console.log('this.data', affix);
            if (typeof affix.id !== 'undefined') {
                other_file = affix.id;
                $('#img-view').html(template('affix-tpl', affix));
            }
        }
    };

    new index();

});